#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (C) 1994  Ling Li
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

import os, xml
from UserList import UserList
from xml.dom import minidom

from coralftp_globals import *

class TransferQueue(UserList):

    def __init__(self, data=None):
        UserList.__init__(self)
        if data != None:
            self.data = data
        return

    def save_to_file(self, filename=None):
        if filename == None:
            config_dir = USERDATADIR
            if not os.path.exists(config_dir):
                os.mkdir(config_dir)
            if not os.path.isdir(config_dir):
                raise IOError, '%s is not a directory' % config_dir
            from time import gmtime, strftime
            filename = strftime("%Y-%m-%d_%H.%M.%S.cfq")
            filename = os.path.join(config_dir, filename)
            
        impl = minidom.getDOMImplementation()
        dom = impl.createDocument(None, "coralftp_queue", None)
        for item in self.data:
            new_node = dom.createElement('item')
            dom.documentElement.appendChild(new_node)
            for key, value in item.items():
                ele = dom.createElement(key)
                ele.appendChild(dom.createTextNode(str(value)))
                new_node.appendChild(ele)
                
        f = file(filename, 'w')
        f.write(dom.toxml(encoding='UTF-8'))
        f.close()
        return

    def load_from_file(self, filename):
        def get_text(nodelist):
            rc = ''
            for n in nodelist:
                if n.nodeType == n.TEXT_NODE:
                    rc = rc + n.data
            return rc

        dom = xml.dom.minidom.parse(filename)
        for item in dom.documentElement.getElementsByTagName('item'):
            if item.parentNode != dom.documentElement: continue
            new_item = {}
            for child in item.childNodes:
                if child.nodeType == child.TEXT_NODE: continue
                name = child.tagName
                value = get_text(child.childNodes)
                new_item[name] = value
            self.data.append(new_item)
        return
